"""
应用主类模块
协调各组件工作，作为应用的入口点
"""

import os
import logging
from typing import Dict, Any, Optional
from datetime import datetime

from .config import CONFIG, load_config, ensure_dir
from .data_processor import DataProcessor
from .report_generator import ReportGenerator

logger = logging.getLogger(__name__)

class Application:
    """应用主类，协调各组件工作"""
    
    def __init__(self, config_path: Optional[str] = None):
        """
        初始化应用
        
        Args:
            config_path: 配置文件路径，如果为None则使用默认配置
        """
        # 加载配置
        self.config = CONFIG.copy()
        if config_path:
            user_config = load_config(config_path)
            self.config.update(user_config)
        
        # 初始化组件
        self.data_processor = DataProcessor(self.config)
        self.report_generator = ReportGenerator(self.data_processor)
        
        # 确保缓存目录存在
        ensure_dir(self.config["cache_dir"])
        
        logger.info("应用初始化完成")
    
    def run(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        运行应用，获取并处理数据
        
        Args:
            endpoint: API端点
            params: 查询参数
            
        Returns:
            处理结果
        """
        logger.info(f"开始运行应用，获取数据: {endpoint}")
        
        # 获取数据
        data = self.data_processor.fetch_data(endpoint, params)
        
        # 确保我们有一个项目列表
        items = data.get("items", [])
        if not isinstance(items, list):
            if isinstance(data, list):
                items = data
            else:
                items = [data]
        
        # 处理数据
        processed_items = self.data_processor.process_items(items)
        
        # 生成报告
        summary_report = self.report_generator.generate_summary_report(processed_items)
        
        # 如果有分组字段，生成分组报告
        group_by = params.get("group_by") if params else None
        if group_by:
            detailed_report = self.report_generator.generate_detailed_report(processed_items, group_by)
        else:
            detailed_report = None
        
        # 返回结果
        result = {
            "raw_count": len(items),
            "processed_count": len(processed_items),
            "summary": summary_report
        }
        
        if detailed_report:
            result["detailed"] = detailed_report
        
        logger.info(f"应用运行完成，处理了 {len(processed_items)} 个项目")
        return result
    
    def export_results(self, results: Dict[str, Any], output_dir: str) -> Dict[str, str]:
        """
        导出结果到文件
        
        Args:
            results: 结果数据
            output_dir: 输出目录
            
        Returns:
            导出的文件路径字典
        """
        ensure_dir(output_dir)
        
        exported_files = {}
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        # 导出摘要报告
        summary_path = os.path.join(output_dir, f"summary_{timestamp}.json")
        if self.report_generator.save_report(results["summary"], summary_path):
            exported_files["summary"] = summary_path
        
        # 如果有详细报告，也导出
        if "detailed" in results:
            detailed_path = os.path.join(output_dir, f"detailed_{timestamp}.json")
            if self.report_generator.save_report(results["detailed"], detailed_path):
                exported_files["detailed"] = detailed_path
        
        # 导出原始数据
        if "items" in results:
            items_path = os.path.join(output_dir, f"items_{timestamp}.json")
            if self.data_processor.export_to_json(results["items"], items_path):
                exported_files["items"] = items_path
            
            # 同时导出CSV格式
            csv_path = os.path.join(output_dir, f"items_{timestamp}.csv")
            if self.data_processor.export_to_csv(results["items"], csv_path):
                exported_files["items_csv"] = csv_path
        
        logger.info(f"导出了 {len(exported_files)} 个文件到 {output_dir}")
        return exported_files
    
    def cleanup(self) -> None:
        """清理资源，如缓存文件"""
        # 清理过期缓存
        cache_dir = self.config["cache_dir"]
        if os.path.exists(cache_dir):
            count = self.data_processor.cache.clear()
            logger.info(f"清理了 {count} 个过期缓存文件")

def main():
    """应用入口点"""
    import argparse
    
    parser = argparse.ArgumentParser(description="数据处理应用")
    parser.add_argument("--config", help="配置文件路径")
    parser.add_argument("--endpoint", required=True, help="API端点")
    parser.add_argument("--output", default="output", help="输出目录")
    parser.add_argument("--group-by", help="分组字段")
    
    args = parser.parse_args()
    
    # 创建应用实例
    app = Application(args.config)
    
    try:
        # 运行应用
        params = {"group_by": args.group_by} if args.group_by else None
        results = app.run(args.endpoint, params)
        
        # 导出结果
        exported_files = app.export_results(results, args.output)
        
        # 打印导出的文件路径
        print("\n导出的文件:")
        for key, path in exported_files.items():
            print(f"{key}: {path}")
        
    except Exception as e:
        logger.error(f"应用运行失败: {e}")
        raise
    finally:
        # 清理资源
        app.cleanup()

if __name__ == "__main__":
    main()